package com.xiaolei.libraryktx

import android.view.animation.Animation
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.xiaolei.library.Exts.Ext


/**
 * 设置动画事件
 */
inline fun <reified T : Animation> T.onAnim(
    noinline onStart: (T.() -> Unit)? = null,
    noinline onEnd: (T.() -> Unit)? = null,
)
{
    this.setAnimationListener(object : Animation.AnimationListener
    {
        override fun onAnimationStart(animation: Animation)
        {
            onStart?.invoke(this@onAnim)
        }

        override fun onAnimationEnd(animation: Animation)
        {
            onEnd?.invoke(this@onAnim)
        }

        override fun onAnimationRepeat(animation: Animation) = Unit
    })
}

/**
 * 动画开始
 */
inline fun <T : Animation> T.onAnimStart(crossinline onStart: () -> Unit)
{
    this.setAnimationListener(object : Animation.AnimationListener
    {
        override fun onAnimationStart(animation: Animation)
        {
            onStart.invoke()
        }

        override fun onAnimationEnd(animation: Animation) = Unit

        override fun onAnimationRepeat(animation: Animation) = Unit
    })
}

/**
 * 动画结束
 */
inline fun <T : Animation> T.onAnimEnd(crossinline onEnd: () -> Unit)
{
    this.setAnimationListener(object : Animation.AnimationListener
    {
        override fun onAnimationStart(animation: Animation) = Unit

        override fun onAnimationEnd(animation: Animation)
        {
            onEnd()
        }

        override fun onAnimationRepeat(animation: Animation) = Unit
    })

}

/**
 * 启动动画
 * 管理在生命周期内的动画，当界面被销毁，则自动取消动画
 * 如果动画支持暂停和恢复，那么也会根据生命周期自动 暂停/恢复。
 */
inline fun <reified T : Animation> T.startWith(owner: FragmentActivity)
{
    Ext.startWith(owner, owner, this)
}

/**
 * 启动动画
 * 管理在生命周期内的动画，当界面被销毁，则自动取消动画
 * 如果动画支持暂停和恢复，那么也会根据生命周期自动 暂停/恢复。
 */
inline fun <reified T : Animation> T.startWith(owner: Fragment)
{
    Ext.startWith(owner, owner, this)
}